<template>
  <div class="sensitive-history">
    <div class="filter-bar">
      <el-select v-model="sensitiveType" placeholder="内容类型" style="width: 120px">
        <el-option label="全部" value="all"></el-option>
        <el-option label="问题" value="question"></el-option>
        <el-option label="回答" value="answer"></el-option>
        <el-option label="评论" value="comment"></el-option>
      </el-select>
      
      <el-select v-model="sensitiveDays" placeholder="时间范围" style="width: 120px; margin-left: 10px;">
        <el-option label="最近7天" :value="7"></el-option>
        <el-option label="最近30天" :value="30"></el-option>
        <el-option label="最近90天" :value="90"></el-option>
        <el-option label="全部" :value="-1"></el-option>
      </el-select>
      
      <el-button type="primary" @click="loadSensitiveHistory" style="margin-left: 10px;">
        <el-icon><Search /></el-icon>查询
      </el-button>
    </div>
    
    <el-table
      v-loading="loading"
      :data="sensitiveHistory"
      style="width: 100%; margin-top: 20px;"
      border
    >
      <el-table-column prop="id" label="ID" width="80"></el-table-column>
      <el-table-column prop="contentType" label="内容类型" width="100">
        <template #default="scope">
          <el-tag :type="getContentTypeTag(scope.row.contentType)">
            {{ getContentTypeText(scope.row.contentType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="contentBrief" label="敏感内容" show-overflow-tooltip>
        <template #default="scope">
          <div v-html="highlightSensitiveWords(scope.row.contentBrief)"></div>
        </template>
      </el-table-column>
      <el-table-column prop="sensitiveDegree" label="敏感程度" width="110">
        <template #default="scope">
          <el-tag :type="getSensitiveLevelTag(scope.row.sensitiveDegree)">
            {{ getSensitiveLevelText(scope.row.sensitiveDegree) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="status" label="处理状态" width="110">
        <template #default="scope">
          <el-tag :type="getStatusTag(scope.row.status)">
            {{ getStatusText(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="检测时间" width="180"></el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="scope">
          <el-button 
            type="primary" 
            size="small" 
            plain 
            @click="viewSensitiveDetail(scope.row)"
          >
            查看
          </el-button>
          <el-button 
            v-if="scope.row.status === 0"
            type="success" 
            size="small" 
            plain 
            @click="approveContent(scope.row.id)"
          >
            通过
          </el-button>
          <el-button 
            v-if="scope.row.status === 0"
            type="danger" 
            size="small" 
            plain 
            @click="rejectSensitive(scope.row.id)"
          >
            拒绝
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <div class="pagination-container">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 50, 100]"
        background
        layout="total, sizes, prev, pager, next"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Search } from '@element-plus/icons-vue';
import { getSensitiveHistory, approveSensitiveContent, rejectSensitiveContent } from '../../api/admin';

// 属性和事件
const props = defineProps({});
const emit = defineEmits(['view-detail']);

// 敏感内容列表
const sensitiveHistory = ref([]);
const total = ref(0);
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const sensitiveType = ref('all');
const sensitiveDays = ref(7);

// 高亮敏感词
const highlightSensitiveWords = (content) => {
  if (!content) return '';
  
  let result = content;
  
  // 后端没有直接返回敏感词列表，使用常见敏感词进行高亮
  const commonSensitiveWords = [
    '暴力', '色情', '赌博', '政治', '诈骗', '违法', '黄赌毒', '侮辱', '仇恨', '恐怖',
    '非法', '歧视', '军火', '黑客', '病毒', '钓鱼', '欺诈', '毒品', '传销', '自杀'
  ];
  
  // 使用常用敏感词进行高亮
  commonSensitiveWords.forEach(word => {
    if (result && result.includes(word)) {
      const regex = new RegExp(word, 'gi');
      result = result.replace(regex, match => `<span class="highlight-sensitive">${match}</span>`);
    }
  });
  
  return result;
};

// 加载敏感内容历史记录
const loadSensitiveHistory = async () => {
  loading.value = true;
  try {
    const params = {
      current: currentPage.value,
      size: pageSize.value,
      type: sensitiveType.value,
      days: sensitiveDays.value
    };
    
    const response = await getSensitiveHistory(params);
    if (response.code === 200) {
      sensitiveHistory.value = response.data.records || [];
      total.value = response.data.total || 0;
    } else {
      ElMessage.error(response.message || '获取敏感内容历史记录失败');
    }
  } catch (error) {
    console.error('获取敏感内容历史记录失败:', error);
    ElMessage.error('获取敏感内容历史记录失败');
  } finally {
    loading.value = false;
  }
};

// 处理分页
const handleSizeChange = (val) => {
  pageSize.value = val;
  loadSensitiveHistory();
};

const handleCurrentChange = (val) => {
  currentPage.value = val;
  loadSensitiveHistory();
};

// 查看敏感内容详情
const viewSensitiveDetail = (content) => {
  emit('view-detail', content);
};

// 通过敏感内容
const approveContent = async (id) => {
  try {
    await ElMessageBox.confirm('确认通过此敏感内容?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const response = await approveSensitiveContent(id);
    if (response.code === 200) {
      ElMessage.success('操作成功');
      loadSensitiveHistory();
    } else {
      ElMessage.error(response.message || '操作失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error);
      ElMessage.error('操作失败');
    }
  }
};

// 拒绝敏感内容
const rejectSensitive = async (id) => {
  try {
    await ElMessageBox.confirm('确认拒绝此敏感内容?', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    const response = await rejectSensitiveContent(id);
    if (response.code === 200) {
      ElMessage.success('操作成功');
      loadSensitiveHistory();
    } else {
      ElMessage.error(response.message || '操作失败');
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('操作失败:', error);
      ElMessage.error('操作失败');
    }
  }
};

// 内容类型标签和文本
const getContentTypeTag = (type) => {
  const types = {
    'question': 'primary',
    'answer': 'success',
    'comment': 'info',
    'default': 'info'
  };
  return types[type] || types.default;
};

const getContentTypeText = (type) => {
  const texts = {
    'question': '问题',
    'answer': '回答',
    'comment': '评论',
    'default': '未知'
  };
  return texts[type] || texts.default;
};

// 敏感程度标签和文本
const getSensitiveLevelTag = (level) => {
  const levels = {
    'high': 'danger',
    'medium': 'warning',
    'low': 'info',
    'default': 'info'
  };
  return levels[level] || levels.default;
};

const getSensitiveLevelText = (level) => {
  const texts = {
    'high': '高',
    'medium': '中',
    'low': '低',
    'default': '未知'
  };
  return texts[level] || texts.default;
};

// 处理状态标签和文本
const getStatusTag = (status) => {
  const statusMap = {
    0: 'warning',
    1: 'success',
    2: 'danger',
    'default': 'info'
  };
  return statusMap[status] || statusMap.default;
};

const getStatusText = (status) => {
  const statusMap = {
    0: '待处理',
    1: '已通过',
    2: '已拒绝',
    'default': '未知'
  };
  return statusMap[status] || statusMap.default;
};

// 生命周期钩子
onMounted(() => {
  loadSensitiveHistory();
});

// 暴露方法给父组件
defineExpose({
  loadSensitiveHistory
});
</script>

<style scoped>
.sensitive-history {
  width: 100%;
}

.filter-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  margin-bottom: 20px;
}

.pagination-container {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

:deep(.highlight-sensitive) {
  color: #F56C6C;
  font-weight: bold;
  background-color: rgba(245, 108, 108, 0.1);
  padding: 0 2px;
  border-radius: 2px;
}

@media (max-width: 768px) {
  .filter-bar {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .filter-bar .el-select {
    width: 100% !important;
    margin-left: 0 !important;
    margin-bottom: 10px;
  }
  
  .filter-bar .el-button {
    margin-left: 0 !important;
  }
}
</style> 